/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.settlement.web.customersettlement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.modules.arecieve.dao.TreceivableDetailDao;
import com.jeesite.modules.arecieve.entity.TreceivableDetail;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.custom.enumInfo.AccountType;
import com.jeesite.modules.order.dao.serviceorder.ServiceOrderDetailDao;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.pay.entity.TpaymentDetail;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prerecieve.dao.TadvancesReceivedEstimatedDao;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.settlement.dao.customercarcontract.CustomerCarContractDao;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlementDetail;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlementPayment;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlementPrepayment;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlement;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementDetail;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementPayment;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementPrepayment;
import com.jeesite.modules.settlement.service.customercarcontract.CustomerCarContractService;
import com.jeesite.modules.settlement.util.CopyObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlement;
import com.jeesite.modules.settlement.service.customersettlement.CustomerSettlementService;

import java.math.BigDecimal;
import java.util.*;

/**
 * 客户结算单Controller
 * @author Kilo
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/settlement/customersettlement/customerSettlement")
public class CustomerSettlementController extends BaseController {

	@Autowired
	private CustomerSettlementService customerSettlementService;

	@Autowired
	private ServiceOrderService serviceOrderService;

	@Autowired
	private ServiceOrderDetailDao serviceOrderDetailDao;

	@Autowired
	private TadvancesReceivedEstimatedDao tadvancesReceivedEstimatedDao;

	@Autowired
	private TreceivableDetailDao treceivableDetailDao;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private FixedExpenseService fixedExpenseService;

	@Autowired
	private CustomerCarContractDao customerCarContractDao;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public CustomerSettlement get(String customerSettlementId, boolean isNewRecord) {
		return customerSettlementService.get(customerSettlementId, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:view")
	@RequestMapping(value = {"list", ""})
	public String list(CustomerSettlement customerSettlement, Model model) {
		model.addAttribute("customerSettlement", customerSettlement);
		return "modules/settlement/customersettlement/customerSettlementList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<CustomerSettlement> listData(CustomerSettlement customerSettlement, HttpServletRequest request, HttpServletResponse response) {
		customerSettlement.setPage(new Page<>(request, response));
		Page<CustomerSettlement> page = customerSettlementService.findPage(customerSettlement);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:view")
	@RequestMapping(value = "form")
	public String form(CustomerSettlement customerSettlement, Model model) {
		customerSettlement = customerSettlementService.get(customerSettlement.getCustomerSettlementId());
        //服务订单处理
		ServiceOrder serviceOrder = serviceOrderService.get(customerSettlement.getServiceOrderId());
		customerSettlement.setServiceOrderId(serviceOrder.getServiceOrderCode());
		//费用项目处理
		List<FixedExpense> fixedExpenseList = fixedExpenseService.findList(new FixedExpense());
		Map<String,String> map = new HashMap<>();
		for (FixedExpense fixedExpense:fixedExpenseList){
			map.put(fixedExpense.getFixedExpenseId(),fixedExpense.getFixedExpenseName());
		}
		for (CustomerSettlementPrepayment customerSettlementPrepayment:customerSettlement.getCustomerSettlementPrepaymentList()){
			customerSettlementPrepayment.setPrepaymentType(map.get(customerSettlementPrepayment.getPrepaymentType()));
		}
		for (CustomerSettlementPayment customerSettlementPayment:customerSettlement.getCustomerSettlementPaymentList()){
			customerSettlementPayment.setExpenseItem(map.get(customerSettlementPayment.getExpenseItem()));
		}
		model.addAttribute("customerSettlement", customerSettlement);
		//获取所有客户信息
		Customer customer = new Customer();
		List<Customer> customerList = customerService.findList(customer);
		model.addAttribute("customerList",customerList);
		//合计信息合计
		List<CustomerSettlementDetail> customerSettlementDetailList = customerSettlement.getCustomerSettlementDetailList();
		double payableAmountTotal = 0d;
		double actualAmountTotal = 0d;
		double stampDutyTotal = 0d;
		double totalAmountTotal = 0d;
		for(CustomerSettlementDetail customerSettlementDetail:customerSettlementDetailList){
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getPayableAmount())){
				payableAmountTotal = NumberUtils.add(payableAmountTotal,customerSettlementDetail.getPayableAmount());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getActualAmount())){
				actualAmountTotal = NumberUtils.add(actualAmountTotal,customerSettlementDetail.getActualAmount());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getStampDuty())){
				stampDutyTotal = NumberUtils.add(stampDutyTotal,customerSettlementDetail.getStampDuty());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getTotalAmount())){
				totalAmountTotal = NumberUtils.add(totalAmountTotal,customerSettlementDetail.getTotalAmount());
			}
		}
		model.addAttribute("payableAmountTotal",payableAmountTotal);
		model.addAttribute("actualAmountTotal",actualAmountTotal);
		model.addAttribute("stampDutyTotal",stampDutyTotal);
		model.addAttribute("totalAmountTotal",totalAmountTotal);

		//payment合计
		List<CustomerSettlementPayment> customerSettlementPaymentList = customerSettlement.getCustomerSettlementPaymentList();
		double actualAmountTotalPayment = 0d;
		for(CustomerSettlementPayment customerSettlementPayment:customerSettlementPaymentList){
			if(ObjectUtils.isNotEmpty(customerSettlementPayment.getActualAmount())){
				actualAmountTotalPayment = NumberUtils.add(actualAmountTotalPayment,customerSettlementPayment.getActualAmount());
			}
		}
		model.addAttribute("actualAmountTotalPayment",actualAmountTotalPayment);

		//供需合同是否生成
        int count = customerCarContractDao.countByCustomerSettlementId(customerSettlement.getCustomerSettlementId());
        if(count>0){
			model.addAttribute("countFlag","1");
		}else{
			model.addAttribute("countFlag","0");
		}
		return "modules/settlement/customersettlement/customerSettlementForm";
	}

	/**
	 * 操作员保存
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:edit")
	@PostMapping(value = "optSave")
	@ResponseBody
	public String optSave(CustomerSettlement customerSettlement) {
		CustomerSettlement customerSettlement1 = customerSettlementService.get(customerSettlement.getCustomerSettlementId());
		customerSettlement1.setInvoiceCustomerId(customerSettlement.getInvoiceCustomerId());
		customerSettlement1.setDate(customerSettlement.getDate());
		customerSettlement1.setRemarks(customerSettlement.getRemarks());
		customerSettlement1.setIsNewRecord(false);
		customerSettlementService.saveFinish(customerSettlement1);
		return renderResult(Global.TRUE, text("保存成功！"));
	}

	/**
	 * 结算完结
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:edit")
	@PostMapping(value = "finishSave")
	@ResponseBody
	public String finishSave(CustomerSettlement customerSettlement) {
		CustomerSettlement customerSettlement1 = customerSettlementService.get(customerSettlement.getCustomerSettlementId());
		customerSettlement1.setFinishFlag("1");
		customerSettlement1.setIsNewRecord(false);
		customerSettlementService.saveFinish(customerSettlement1);
		return renderResult(Global.TRUE, text("结算完结成功！"));
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:view")
	@RequestMapping(value = "detail")
	public String detail(CustomerSettlement customerSettlement, Model model) {
		customerSettlement = customerSettlementService.get(customerSettlement.getCustomerSettlementId());
		//服务订单处理
		ServiceOrder serviceOrder = serviceOrderService.get(customerSettlement.getServiceOrderId());
		customerSettlement.setServiceOrderId(serviceOrder.getServiceOrderCode());
		model.addAttribute("customerSettlement", customerSettlement);
		//费用项目处理
		List<FixedExpense> fixedExpenseList = fixedExpenseService.findList(new FixedExpense());
		Map<String,String> map = new HashMap<>();
		for (FixedExpense fixedExpense:fixedExpenseList){
			map.put(fixedExpense.getFixedExpenseId(),fixedExpense.getFixedExpenseName());
		}
		for (CustomerSettlementPrepayment customerSettlementPrepayment:customerSettlement.getCustomerSettlementPrepaymentList()){
			customerSettlementPrepayment.setPrepaymentType(map.get(customerSettlementPrepayment.getPrepaymentType()));
		}
		for (CustomerSettlementPayment customerSettlementPayment:customerSettlement.getCustomerSettlementPaymentList()){
			customerSettlementPayment.setExpenseItem(map.get(customerSettlementPayment.getExpenseItem()));
		}
		//获取所有客户信息
		Customer customer = new Customer();
		List<Customer> customerList = customerService.findList(customer);
		model.addAttribute("customerList",customerList);
		//合计信息合计
		List<CustomerSettlementDetail> customerSettlementDetailList = customerSettlement.getCustomerSettlementDetailList();
		double payableAmountTotal = 0d;
		double actualAmountTotal = 0d;
		double stampDutyTotal = 0d;
		double totalAmountTotal = 0d;
		for(CustomerSettlementDetail customerSettlementDetail:customerSettlementDetailList){
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getPayableAmount())){
				payableAmountTotal = NumberUtils.add(payableAmountTotal,customerSettlementDetail.getPayableAmount());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getActualAmount())){
				actualAmountTotal = NumberUtils.add(actualAmountTotal,customerSettlementDetail.getActualAmount());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getStampDuty())){
				stampDutyTotal = NumberUtils.add(stampDutyTotal,customerSettlementDetail.getStampDuty());
			}
			if(ObjectUtils.isNotEmpty(customerSettlementDetail.getTotalAmount())){
				totalAmountTotal = NumberUtils.add(totalAmountTotal,customerSettlementDetail.getTotalAmount());
			}
		}
		model.addAttribute("payableAmountTotal",payableAmountTotal);
		model.addAttribute("actualAmountTotal",actualAmountTotal);
		model.addAttribute("stampDutyTotal",stampDutyTotal);
		model.addAttribute("totalAmountTotal",totalAmountTotal);

		//payment合计
		List<CustomerSettlementPayment> customerSettlementPaymentList = customerSettlement.getCustomerSettlementPaymentList();
		double actualAmountTotalPayment = 0d;
		for(CustomerSettlementPayment customerSettlementPayment:customerSettlementPaymentList){
			if(ObjectUtils.isNotEmpty(customerSettlementPayment.getActualAmount())){
				actualAmountTotalPayment = NumberUtils.add(actualAmountTotalPayment,customerSettlementPayment.getActualAmount());
			}
		}
		model.addAttribute("actualAmountTotalPayment",actualAmountTotalPayment);
		//供需合同是否生成
		int count = customerCarContractDao.countByCustomerSettlementId(customerSettlement.getCustomerSettlementId());
		if(count>0){
			model.addAttribute("countFlag","1");
		}else{
			model.addAttribute("countFlag","0");
		}
		return "modules/settlement/customersettlement/customerSettlementDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:edit")
	@PostMapping(value = "submitSave")
	@ResponseBody
	public String submitSave(String serviceOrderId,String frameNumbersStr) {
		CustomerSettlement customerSettlement = new CustomerSettlement();
		//配置主表信息
		customerSettlement.setServiceOrderId(serviceOrderId);
		ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
		CopyObjectUtil.copyProperties(serviceOrder,customerSettlement,true);
		customerSettlement.setInvoiceCustomerId(customerSettlement.getCustomerId());
		customerSettlement.setFinishFlag("0");

		//获取固定费用相关信息
		FixedExpense fixedExpense1 = fixedExpenseService.get(AccountType.XSFWF.getCode());
		double basicExpense = fixedExpense1.getSalesPrice();
		FixedExpense fixedExpense2 = fixedExpenseService.get(AccountType.KPYHS.getCode());
		double radio = Double.parseDouble(fixedExpense2.getSalesPriceRatio());
		radio = NumberUtils.mul(radio,0.01d);

		//detail子表信息
		List<CustomerSettlementDetail> customerSettlementDetailList = new ArrayList<>();
		Map<String,Object> paramsMap = new HashMap<>();
		paramsMap.put("serviceOrderId",serviceOrder.getServiceOrderId());
		String[] frameNumberArr = frameNumbersStr.split(",");
		List<String> frameNumberList = Arrays.asList(frameNumberArr);
		paramsMap.put("frameNumbers",frameNumberList);
		List<Map<String,Object>> mainList = serviceOrderDetailDao.getCarJSReport(paramsMap);
		//记录实际金额
		double rActualApAmountRecord = 0d;
		for(Map<String,Object> mainMap:mainList){
			CustomerSettlementDetail customerSettlementDetail = new CustomerSettlementDetail();
			if(ObjectUtils.isNotEmpty(mainMap.get("carId"))) {
				customerSettlementDetail.setCarId(String.valueOf(mainMap.get("carId")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("frameNumber"))) {
				customerSettlementDetail.setFrameNumber(String.valueOf(mainMap.get("frameNumber")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("amount"))) {
				customerSettlementDetail.setPrice(((BigDecimal)mainMap.get("amount")).doubleValue());
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("currency"))) {
				customerSettlementDetail.setCurrency(String.valueOf(mainMap.get("currency")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("tentativeExchangeRate"))) {
				customerSettlementDetail.setEstimateExchangeRate(String.valueOf(mainMap.get("tentativeExchangeRate")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("investorRealExchangeRate"))) {
				customerSettlementDetail.setActualExchangeRate(String.valueOf(mainMap.get("investorRealExchangeRate")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("rApAmount"))) {
				customerSettlementDetail.setPayableAmount(((BigDecimal)mainMap.get("rApAmount")).doubleValue());
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("rActualApAmount"))) {
				customerSettlementDetail.setActualAmount(((BigDecimal)mainMap.get("rActualApAmount")).doubleValue());
				rActualApAmountRecord = ((BigDecimal)mainMap.get("rActualApAmount")).doubleValue();
				//印花税
				customerSettlementDetail.setStampDuty(NumberUtils.add(basicExpense,NumberUtils.mul(rActualApAmountRecord,radio)));
				//总金额
				customerSettlementDetail.setTotalAmount(NumberUtils.add(rActualApAmountRecord,customerSettlementDetail.getStampDuty()));
			}
			//印花税与总金额目前尚未知晓
			customerSettlementDetailList.add(customerSettlementDetail);
		}
		customerSettlement.setCustomerSettlementDetailList(customerSettlementDetailList);

		//prepayment子表信息
		List<CustomerSettlementPrepayment> customerSettlementPrepaymentList = new ArrayList<>();
		//预收款信息列表
		List<TadvancesReceivedEstimated> tadvancesReceivedEstimatedList = tadvancesReceivedEstimatedDao.findAdvancesReceivedEstimatedInfo(frameNumberList);
		//获取预收客户余额总金额
		double paymentAmountEstimatedBalance = 0d;
		for (TadvancesReceivedEstimated tadvancesReceivedEstimated:tadvancesReceivedEstimatedList){
			CustomerSettlementPrepayment customerSettlementPrepayment = new CustomerSettlementPrepayment();
			CopyObjectUtil.copyProperties(tadvancesReceivedEstimated,customerSettlementPrepayment,true);
			if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated.getAdvancesReceivedCode())){
				customerSettlementPrepayment.setPrepaymentCode(tadvancesReceivedEstimated.getAdvancesReceivedCode());
			}
			if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated.getAdvancesReceivedType())){
				customerSettlementPrepayment.setPrepaymentType(tadvancesReceivedEstimated.getAdvancesReceivedType());
			}
			if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated.getReceivedSumActual())) {
				customerSettlementPrepayment.setAmount(tadvancesReceivedEstimated.getReceivedSumActual());
			}
			if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated.getReceivedAmountActual())) {
				customerSettlementPrepayment.setVerificationAmount(tadvancesReceivedEstimated.getReceivedAmountActual());
			}
			if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated.getReceivedAmountEstimated())) {
				customerSettlementPrepayment.setRemainingAmount(tadvancesReceivedEstimated.getReceivedAmountEstimated());
			}
			paymentAmountEstimatedBalance = NumberUtils.add(paymentAmountEstimatedBalance,tadvancesReceivedEstimated.getReceivedAmountEstimated());
			customerSettlementPrepaymentList.add(customerSettlementPrepayment);
		}

		//获取客户预收款余额
		TadvancesReceivedEstimated tadvancesReceivedEstimated1 = tadvancesReceivedEstimatedDao.sumReceivedAmountEstimatedByCustomerId(customerSettlement.getCustomerId());
		if(ObjectUtils.isNotEmpty(tadvancesReceivedEstimated1.getReceivedAmountEstimated())){
			customerSettlement.setCustomerPrepaymentBalance(tadvancesReceivedEstimated1.getReceivedAmountEstimated());
		}else{
			customerSettlement.setCustomerPrepaymentBalance(0d);
		}
		customerSettlement.setOrderPrepaymentBalance(paymentAmountEstimatedBalance);
		customerSettlement.setCustomerSettlementPrepaymentList(customerSettlementPrepaymentList);

		//payment子表信息
		List<CustomerSettlementPayment> customerSettlementPaymentList = new ArrayList<>();
		//收款信息
		List<TreceivableDetail> treceivableDetailList = treceivableDetailDao.selectTreceivableDetailInfo(frameNumberList);
		for(TreceivableDetail treceivableDetail:treceivableDetailList){
			CustomerSettlementPayment customerSettlementPayment = new CustomerSettlementPayment();
			CopyObjectUtil.copyProperties(treceivableDetail,treceivableDetailList,true);
			if(ObjectUtils.isNotEmpty(treceivableDetail.getActualArAmount())) {
				customerSettlementPayment.setActualAmount(treceivableDetail.getActualArAmount());
			}
			customerSettlementPayment.setIfFlag(treceivableDetail.getAdvancesReceivedCode());
			customerSettlementPaymentList.add(customerSettlementPayment);
		}
		customerSettlement.setCustomerSettlementPaymentList(customerSettlementPaymentList);
		customerSettlementService.save(customerSettlement);
		return customerSettlement.getCustomerSettlementId();
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated CustomerSettlement customerSettlement) {
		customerSettlementService.save(customerSettlement);
		return renderResult(Global.TRUE, text("保存客户结算单成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("settlement:customersettlement:customerSettlement:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(CustomerSettlement customerSettlement) {
		customerSettlementService.delete(customerSettlement);
		return renderResult(Global.TRUE, text("删除客户结算单成功！"));
	}

}
